#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Computer{
public:
    Computer(const char * brand, float price)
    :_brand(new char[strlen(brand) + 1]())
    ,_price(price)
    {
        strcpy(_brand ,brand);
    }

    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
    }
    //拷贝构造函数
    Computer(const Computer & rhs)
    :_brand(new char[strlen(rhs._brand) + 1]())
    ,_price(rhs._price)
    {
        strcpy(_brand, rhs._brand);
        cout << "Computer(const Computer & ) " << endl;
    }

    //赋值运算符函数--编译器默认会提供
    //又是因为默认执行了浅拷贝，导致了double free
    //void operator=(const Computer & rhs){
    Computer & operator=(Computer & rhs){
        cout << "operator=(const Computer &)" << endl;
        //还需要考虑一些边界条件 不是自己给自己赋值
        if(this != &rhs){
            //先回收左操作数操作的堆空间
            delete [] _brand;
            //执行深拷贝
            //先处理_brand
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand, rhs._brand);
            //随后去处理_price
            _price = rhs._price;
        }
        return *this;
    }

    void print(){
        cout << "_brand=" << _brand << ",_price=" << _price << endl;
    }

private:
    char * _brand;
    float _price;
};
void test(){
    Computer c1("Apple", 12000), c2("Huawei", 7800);
    //下面两行代码的效果是完全等价的
    c1 = c2;
    c1.operator=(c2);
    //c1 = c2 = c3;如果返回值是void那么无法处理连续赋值
    c1.print();
    c2.print();
}
void test2(){
    Computer c1("Apple", 12000), c2("Huawei", 7800);
    c1 = c1;
    c1.print();
}

void test3(){
    Computer c1("apple", 12000);
    //非const引用无法绑定右值
    c1 = Computer("mi", 4500);
}

int main()
{
    test2();
    return 0;
}

